<template>
  <div class="agentList divBox">
    <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
      <el-tab-pane label="用户排行榜" name="users"></el-tab-pane>
      <el-tab-pane label="公司排行榜" name="company"></el-tab-pane>
    </el-tabs>
    <el-card class="box-card" shadow="hover">
      <template class="clearfix" v-slot:header v-if="rankType == 1">
        <el-tooltip :disabled="!disabled" class="ml10" effect="dark" content="本页至少选择一项"
          placement="bottom">
          <div style="display: inline-block">
            <el-button :disabled="disabled" size="small" icon="el-icon-close" type="primary"
              @click="delectAll(null)">批量删除活动</el-button>
          </div>
        </el-tooltip>
      </template>
      <el-table :data="rankType == 1 ? tableData : companyData" v-loading="disLoading"
        style="width: 100%" size="mini" class="table" @selection-change="handleSelectionChange"
        @sort-change='sortTableFun'>
        <el-table-column type="selection" min-width="55"></el-table-column>
        <template v-if="rankType == 1">
          <el-table-column prop="id" label="排行榜ID" width="80">
          </el-table-column>
          <el-table-column prop="userId" label="用户ID" width="120">
          </el-table-column>
          <el-table-column prop="user.nickName" label="用户昵称" width="120">
          </el-table-column>
          <el-table-column prop="user.realName" label="用户名称" width="120">
          </el-table-column>
          <el-table-column prop="activityId" label="活动ID" width="180">
          </el-table-column>
        </template>
        <template v-else-if="rankType == 0">
          <el-table-column prop="companyId" label="公司ID" width="80">
          </el-table-column>
          <el-table-column prop="companyName" label="公司名称" width="120">
          </el-table-column>
        </template>
        <el-table-column prop="likeTotal" label="点赞数" width="120" sortable='custom'>
        </el-table-column>
        <el-table-column prop="realLikeTotal" label="真实点赞数" width="160" sortable='custom'>
        </el-table-column>
        <el-table-column prop="commentTotal" label="评论数" width="140" sortable='custom'>
        </el-table-column>
        <el-table-column prop="realCommentTotal" label="真实评论数" width="180" sortable='custom'>
        </el-table-column>
        <el-table-column prop="browseMovieTotal" label="浏览电影总数" width="180" sortable='custom'>
        </el-table-column>
        <el-table-column prop="realBrowseMovieTotal" label="真实浏览电影总数" width="220" sortable='custom'>
        </el-table-column>
        <el-table-column prop="total" label="总条数" width="100" sortable='custom'>
        </el-table-column>
        <el-table-column prop="realTotal" label="真实总条数" width="120" sortable='custom'>
        </el-table-column>
        <el-table-column prop="createDateUTC" label="更新时间" width="200" v-if="rankType == 1">
          <template slot-scope="scope">
            {{ new Date(scope.row.createDateUTC).toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="260" fixed="right" align="center">
          <template slot-scope="{ row }">
            <el-button type="text" size="small" @click="edit(row.userId)" v-if="rankType == 1">
              编辑内容
            </el-button>
            <el-divider direction="vertical" />
            <el-button type="text" size="small" @click="delectAll(row.userId)" v-if="rankType == 1">
              删除数据
            </el-button>
            <el-divider direction="vertical"></el-divider>
            <el-dropdown class="ml10" placement="bottom">
              <span class="el-dropdown-link">
                显示类型<i class="el-icon-arrow-down el-icon--right" />
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item @click.native="showType(0)">首页
                </el-dropdown-item>
                <el-dropdown-item @click.native="showType(1)">公司
                </el-dropdown-item>
                <el-dropdown-item @click.native="showType(2)">用户
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>

        </el-table-column>
      </el-table>
      <div class="spreadBox">
        <pagination v-show="pagination.total > 0" :total="pagination.total"
          :page.sync="pagination.page" :limit.sync="pagination.limit" :page-sizes="[10, 20, 30, 50]"
          @pagination="replyChange" />
      </div>
    </el-card>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import {
  getUserRankListApi,
  getCompanyRankListApi,
  deleteUserAllApi,
} from '@/api/interaction';
export default {
  data() {
    return {
      tableData: [],
      companyData: [],
      pagination: {
        page: 1,
        limit: 10,
        total: 10,
      },
      del: null,
      disabled: null,
      activeName: 'users',
      disLoading: false,
      rankType: 1, // 1是用户0表示公司
      type: 1, // 类型（0首页 1公司 2用户）
      targetId: 1, // 场景Id,根据Type类型决定是userId还是companyId
      orderby: 'total desc',
    };
  },
  computed: {
    ...mapGetters(['selectedId']),
  },
  mounted() {
    this.getRankList();
  },
  methods: {
    showType(type) {
      this.type = type;
      this.getRankList();
    },
    sortTableFun(column) {
      console.log('column', column);
      // 用户点击这一列的上下排序按钮时，触发的函数
      let order;
      let props = column.prop;
      if (props) {
        // 该列有绑定prop字段走这个分支
        if (column.order == 'ascending') {
          // 当用户点击的是升序按钮，即ascending时
          order = 'asc'; // 将order这个变量赋值为后端接口文档定义的升序的字段名，之后作为入参传给后端
        } else if (column.order == 'descending') {
          // 当用户点击的是升序按钮，即descending时
          order = 'desc'; // 将order这个变量赋值为后端接口文档定义的降序的字段名，之后作为入参传给后端
        }
        this.orderby = `${props} ${order}`; // 重新接排序字段和排序方向，作为入参传给后端
        if (order == null) {
          this.orderby = 'total desc'; // 如果没有排序方向，默认按total降序排序
        }
        console.log('orderby', this.orderby);
        this.getRankList();
      }
    },

    async getRankList() {
      this.disLoading = true;
      if (this.rankType == 1) {
        await getUserRankListApi(this.selectedId, {
          pageNumber: this.pagination.page,
          pageSize: this.pagination.limit,
          orderby: this.orderby,
          // targetId: this.targetId,
          type: this.type,
        })
          .then((res) => {
            this.$set(this, 'tableData', res.data);
            this.pagination.total = res.head ? res.head.totalCount : 0;
            console.log('getUserRankListApi', this.tableData);
            this.disLoading = false;
          })
          .catch(() => {
            this.disLoading = false;
          });
      } else if (this.rankType == 0) {
        await getCompanyRankListApi(this.selectedId, {
          pageNumber: this.pagination.page,
          pageSize: this.pagination.limit,
          orderby: this.orderby,
          // targetId: this.targetId,
          type: this.type,
        })
          .then((res) => {
            // this.$set(this, 'companyData', res.data);
            this.companyData = res.data;
            this.pagination.total = res.head ? res.head.totalCount : 0;
            console.log('getCompanyRankListApi', this.companyData);
            this.disLoading = false;
          })
          .catch(() => {
            this.disLoading = false;
          });
      }
    },
    /**
     * 行选中时
     */
    handleSelectionChange(val) {
      this.$set(
        this,
        'del',
        val.map((item) => item.id)
      );
      console.log(this.del);
      if (val.length > 0) this.$set(this, 'disabled', false);
      else this.$set(this, 'disabled', true);
    },
    replyChange(reply) {
      this.$set(this.pagination, 'page', reply.page);
      this.$set(this.pagination, 'limit', reply.limit);
      console.log('pagination', this.pagination);
      this.getRankList();
    },
    edit(id) {
      console.log('edit>>>>>>>>>', id);
      const _this = this;
      _this.$modal({
        componentProps: {
          selectedId: _this.selectedId,
          editId: id,
        },
        component: (resolve) => require(['./components/statistics'], resolve),
        // component: () => import('./components/statistics'),
        props: {
          title: '编辑',
          customClass: 'zdyDialogCls editAgentDialogCls',
          width: '100%',
          closeOnClickModal: false,
        },
        methods: {
          getRolesList() {
            _this.getRankList();
          },
        },
      });
    },
    delectAll(id) {
      console.log('delectAll', id);
      let params = {
        userIds: !id ? `${this.del.join()}` : id,
      };
      id || (this.del.length !== 0 && !this.disabled)
        ? this.$confirm('删除活动', {
            title: '删除活动',
            message: this.$createElement(
              'div',
              null,
              ['确定要删除活动吗？', '删除活动后将无法恢复，请谨慎操作！'].map(
                (item) => this.$createElement('p', null, item)
              )
            ),
            showCancelButton: true,
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          })
            .then(() => {
              console.log('删除的id:', id);
              deleteUserAllApi(this.selectedId, params).then((res) => {
                if (!id && res) return this.$message.warning(res);
                this.$message.success('删除活动成功！');
                this.getRankList();
              });
            })
            .catch(() => {
              this.$message({
                type: 'info',
                message: '已取消删除活动',
              });
            })
        : this.$message.warning('请至少选择一条数据');
    },
    handleClick(tab, event) {
      if (tab.name == 'users') {
        this.$set(this, 'rankType', 1);
      } else if (tab.name == 'company') {
        this.$set(this, 'rankType', 0);
      }
      this.getRankList();
      console.log('tab>>>>>>>>', tab.name);
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-tabs--card > .el-tabs__header {
  margin: 0 !important;
}
</style>
